<template>
  <div class="dynamic-container">
    <!-- <el-button @click="closeTag">关闭</el-button> -->
    <spsMaster ref="spsMaster" :queryParams="selectedRow" @back="closeTag"></spsMaster>
  </div>
</template>

<script>
import spsMaster from '@/components/SpsPublic/Master/SpsMaster'
import { baseListRetrieveCondition } from '@/api/mis/retrievecondition'
import { listMisView } from '@/components/SpsPublic/Dynamic/misView.js'
import { getBaseFunction } from '@/api/mis/function'
import BreadCrumb from '@/components/SpsPublic/BreadCrumb/BreadCrumb'
import store from '@/store/index'
import { getFunNo } from '@/utils/party'
import { permissionByFunNo } from '@/api/system/menu.js'
import { decrypt } from '@/utils/aesCrypto'

export default {
  name: 'PublicRecord',
  components: {
    spsMaster,
    BreadCrumb,
  },
  computed: {
    tableHeight() {
      return store.state.dynamic.tableHeight
    },
    visitedViews() {
      return this.$store.state.tagsView.visitedViews
    },
  },
  data() {
    return {
      permissionPrefix: 'dynamic:button:',
      store: store,
      timer: 0,
      dynamicData: {
        searchData: [],
        viewData: [],
        buttonData: {
          add: true,
          update: true,
          delete: true,
        },
        addFormData: {
          title: '',
          formData: [],
        },
        updateData: {},
        handleType: 'view',
        conType: {
          datePicker: 'el-date-picker',
          treeSelect: 'mis-select-tree',
        },
      },
      queryParams: {
        pageNum: 1,
        pageSize: 20,
        ctFunNo: getFunNo(this.$route),
        queryType: 'Q',
      },
      selectedRow: {
        selectedCt: null,
        funNo: getFunNo(this.$route),
        functionData: {},
        backChangeClose: true,
      },
      showMaster: false,
      dateFormat: '{y}-{m}-{d}',
      routeQueryParam: {
        ctFunNo: this.$route.query.ctFunNo,
        ctIfEnd: this.$route.query.ctIfEnd == 'true',
        ctId: this.$route.query.ctId,
        handleType: this.$route.query.handleType,
      },
      fromPath: undefined,
    }
  },
  created() {
    // 获取url中的参数
    try {
      //debugger
      this.routeQueryParam = decrypt(this.$route.query.id)
    } catch (error) {
      console.log(error)
      this.$router.push('/401')
    }

    const that = this
    this.selectedRow = {
      selectedCt: {
        ct_fun_no: this.routeQueryParam.ctFunNo,
        ct_end_name:
          this.routeQueryParam.ctIfEnd == 'true' ? '已签发' : '未签发',
        ct_id: this.routeQueryParam.ctId,
      },
      funNo: this.routeQueryParam.ctFunNo,
      functionData: {},
      backChangeClose: true,
    }
    this.getViewableAction()
    store
      .dispatch('createSingleStore', that.queryParams.ctFunNo)
      .then(() => {
        if (that.routeQueryParam.handleType != 'view') {
          store.dispatch('setHandleType', {
            funNo: that.queryParams.ctFunNo,
            handleType: 'edit',
          })
        }
      })
      .then(() => {
        this.passToMaster(that.routeQueryParam.ctFunNo)
      })

    const subSingleStore = {
      funNo: that.queryParams.ctFunNo,
      subFunNo: this.routeQueryParam.ctFunNo,
      oldForm: {},
      newForm: {},
      ctId: this.routeQueryParam.ctId,
      changeForm: false,
      ifEnd: this.routeQueryParam.ctIfEnd,
    }
    // 初始化subSingleStore
    store.dispatch('createSubSingleStore', subSingleStore).then(() => {
      store.dispatch('setCtId', subSingleStore)
    })
    permissionByFunNo(this.queryParams.ctFunNo).then((response) => {
      if (response && response.code === 200) {
        this.permissionPrefix = response.data
      }
    })
  },
  // 路由进入前，记录路由信息
  beforeRouteEnter(to, from, next) {
    next((vm) => {
      // 通过 `vm` 访问组件实例,将值传入fromPath
      vm.fromPath = from.fullPath
    })
  },
  methods: {
    getViewableAction() {
      //debugger
      if (
        this.$store.getters.name != this.routeQueryParam.name &&
        this.$store.getters.name.indexOf('admin') == -1
      ) {
        this.$router.push('/401')
      }
    },
    // 获取该功能的数据
    getFunctionData() {
      const promise = new Promise((resolve, reject) => {
        getBaseFunction(this.queryParams.ctFunNo).then((response) => {
          this.selectedRow.functionData = response.data
          const pageSize = response.data.amRow
          if (pageSize && pageSize > 0 && pageSize <= 100) {
            this.queryParams.pageSize = pageSize
          }
          store.dispatch('setCtFun', this.selectedRow.functionData)
          resolve()
        })
      })
      const that = this
      promise.then(() => {
        that.$refs.dySearch.postForm()
      })
    },
    onResize() {
      this.timer && clearTimeout(this.timer)
      this.timer = setTimeout(() => {
        this.gettableheight()
      }, 500)
    },
    closeTag() {
      this.$store
        .dispatch('tagsView/delView', this.$route)
        .then(({ visitedViews }) => {
          this.toLastView(visitedViews, this.$route)
        })
    },
    toLastView(visitedViews, view) {
      const latestView = visitedViews.slice(-1)[0]
      console.log(this.fromPath)
      if (latestView) {
        this.$router.push(this.fromPath)
      } else {
        // now the default is to redirect to the home page if there is no tags-view,
        // you can adjust it according to your needs.
        if (view.name === 'Dashboard') {
          // to reload home page
          this.$router.replace({ path: '/redirect' + view.fullPath })
        } else {
          this.$router.push('/')
        }
      }
    },
    isActive(route) {
      return route.path === this.$route.path
    },
    gettableheight() {
      this.$nextTick(function () {
        var tableHeight = this.$refs.contextCard.$el.offsetHeight - 70
        store.dispatch('setTabelHeight', tableHeight)
      })
    },
    // 传值至spsMaster
    passToMaster(value) {
      this.selectedRow.selectedCt.ct_fun_no = value
      this.$refs['spsMaster'].resetTabSelected()
      this.$refs['spsMaster'].refresh()
    },
    // 切换master显示
    switchShowMaster(refreshFlag) {
      // master中数据保存，则刷新列表
      if (refreshFlag) {
        this.$refs.dyList.getList()
      }
      this.showMaster =
        store.getters.singleStore['main' + this.selectedRow.funNo].showMaster
    },
    // 获取表格显示列
    getMisView() {
      this.loading = true
      listMisView(this.queryParams).then((response) => {
        this.dynamicData.viewData = response.rows
        this.dynamicData.viewData = this.dynamicData.viewData.filter(
          (column) => {
            return column.ctIfTable == '1'
          }
        )
        this.loading = false
      })
    },
    // 获取搜索查询信息数据
    getRetrieve() {
      baseListRetrieveCondition(this.queryParams).then((response) => {
        this.dynamicData.searchData = response.rows
        // 包含下级元素的位置
        let index = -1
        let checkValue = true
        for (let i = 0; i < this.dynamicData.searchData.length; i++) {
          const item = this.dynamicData.searchData[i]
          if (
            item.ctConType == this.dynamicData.conType.treeSelect &&
            item.ctConTreetype == '99'
          ) {
            checkValue = item.ctColDefaultv == '1'
            //  组织的下拉查询，赋登录人的管辖范围初始值
            item.ctColDefaultv = store.state.user.branchInfo.manageBranchLevel
            index = i + 1
          }
        }
        if (index != -1) {
          const retrieve = {
            ctConType: 'el-checkbox',
            ctColDefaultv: checkValue,
            ctColName: 'includeFlag',
            ctColTitle: '',
          }
          this.dynamicData.searchData.splice(index, 0, retrieve)
        }
        // 获取该功能的数据
        this.getFunctionData()
      })
    },
    // 查询表格数据
    getList(val) {
      var keys = Object.keys(val)
      for (var i = 0; i < keys.length; i++) {
        this.queryParams[keys[i]] = val[keys[i]]
      }
      this.$refs['dyList'].getList()
    },
    //删除操作
    handleRemove() {
      this.$refs.dyList.handleDelete()
    },
  },
}
</script>

<style>
.box-card {
  /* padding: 5px; */
  margin: 4px 10px 4px 10px;
}
.dynamicSearch {
  overflow: visible;
}

.card-bread-crumb {
  margin-left: 11px;
  margin-bottom: 3px;
}

.dynamicList {
  position: relative;
}
</style>
